﻿using SuporeSliplampApp.Control;
using SuporeSliplampApp.Models;
using SuporeSliplampApp.ViewModels;
using SuporeSliplampApp.Service;
using SuporeSliplampApp.Util;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using Microsoft.Win32;
using ControlzEx.Standard;
using Supore.APP.UI.Controls.Notify;

namespace SuporeSliplampApp.Views
{
    /// <summary>
    /// CSVView.xaml 的交互逻辑
    /// </summary>
    public partial class CSVView : Window
    {

        AddPatientService service = new AddPatientService();

        private enum DataSourceType { CSV, Database }
        private DataSourceType currentDataSourceType;

        List<PatientModel> patientList = new List<PatientModel>();
        ObservableCollection<PatientModel> bindList = new ObservableCollection<PatientModel>();
        AddPatientService patientService = new AddPatientService();
        OpenPatientsModel openPatientsModel = new OpenPatientsModel();

        public CSVView()
        {
            InitializeComponent();

            selectAllCheckBox.Checked += SelectAllCheckBox_Checked;
            selectAllCheckBox.Unchecked += SelectAllCheckBox_Unchecked;

            this.DataContext = this;
            if (Common.languageCode == "zh-CN")
            {
                title.Text = "导入导出CSV";
            }
            else
            {
                title.Text = "Import and export CSV files";
            }
            //title.Text = "导入导出CSV";
            pathgrid.Visibility = Visibility.Collapsed;
            selectAllCheckBox.Visibility = Visibility.Collapsed;
            ImpSelBtn.Visibility = Visibility.Collapsed;
        }

        private void combox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!this.IsLoaded) return;

            if (modeselect.SelectedIndex == 0)
            {
                if (Common.languageCode == "zh-CN")
                {
                    title.Text = "导入CSV";
                }
                else
                {
                    title.Text = "Import CSV files";
                }
                pathgrid.Visibility = Visibility.Visible;
                selectAllCheckBox.Visibility = Visibility.Collapsed;
                ImpSelBtn.Visibility= Visibility.Collapsed;

                currentDataSourceType = DataSourceType.CSV;
                openPatientsModel.RecordCount = bindList.Count;
                LoadDataWithPagination(1, openPatientsModel.PageSize);
            }
            else if (modeselect.SelectedIndex == 1)
            {
                if (Common.languageCode == "zh-CN")
                {
                    title.Text = "病人列表";
                }
                else
                {
                    title.Text = "Patient List";
                }
                pathgrid.Visibility = Visibility.Collapsed;
                selectAllCheckBox.Visibility = Visibility.Visible;
                ImpSelBtn.Visibility = Visibility.Visible;

                currentDataSourceType = DataSourceType.Database;
                patientList = getPatient();
                openPatientsModel.RecordCount = patientList.Count;
                LoadDataWithPagination(1, openPatientsModel.PageSize);
            }
        }


        private void SelectAllCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            foreach (var patient in patientList)
            {
                patient.IsSelected = true;
            }
        }

        private void SelectAllCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            foreach (var patient in patientList)
            {
                patient.IsSelected = false; 
            }
        }



        private void OpenPath_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*"
            };
            if (openFileDialog.ShowDialog() == true)
            {
                // 将路径显示到TextBox
                ((TextBox)pathgrid.Children[1]).Text = openFileDialog.FileName;
            }
        }

        private void ImportBtn_Click(object sender, RoutedEventArgs e)
        {
            string filePath = ((TextBox)pathgrid.Children[1]).Text;

            if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
            {
                try
                {
                    var lines = File.ReadAllLines(filePath, Encoding.Default);
                    if (lines.Length > 0)
                    {
                        // 清空当前的数据
                        bindList.Clear();

                        // 开始从第二行读取数据，第一行通常是头部
                        for (int i = 1; i < lines.Length; i++)
                        {
                            var data = lines[i].Split(',');
                            if (data.Length >= 8)
                            {
                                PatientModel patient = new PatientModel
                                {
                                    Name = data[0],
                                    P_ID = data[1],
                                    SEX = data[2],
                                    Birth = DateTime.Parse(data[3]),
                                    Adreess = data[4],
                                    PhoneNum = data[5],
                                    Email = data[6],
                                    InsertDate = DateTime.Parse(data[7])
                                };

                                if (string.IsNullOrEmpty(patient.Name))
                                {
                                    if (Common.languageCode == "zh-CN")
                                    {
                                        LayUINotify.ShowInfo("姓名不能为空!");
                                    }
                                    else
                                    {
                                        LayUINotify.ShowInfo("Tip", "Name is required!");
                                    }
                                    //LayUINotify.ShowInfo("姓名不能为空!");
                                    return;
                                }
                                if (string.IsNullOrEmpty(patient.P_ID))
                                {
                                    if (Common.languageCode == "zh-CN")
                                    {
                                        LayUINotify.ShowInfo("病人ID不能为空！");
                                    }
                                    else
                                    {
                                        LayUINotify.ShowInfo("Tip", "ID is required!");
                                    }
                                    //LayUINotify.ShowInfo("病人ID不能为空！");
                                    return;
                                }
                                if (string.IsNullOrEmpty(patient.Birth.ToString()))
                                {
                                    if (Common.languageCode == "zh-CN")
                                    {
                                        LayUINotify.ShowInfo("生日不能为空！");
                                    }
                                    else
                                    {
                                        LayUINotify.ShowInfo("Tip", "Birthday is required!");
                                    }
                                    //LayUINotify.ShowInfo("生日不能为空！");
                                    return;
                                }
                                if (string.IsNullOrEmpty(patient.SEX))
                                {
                                    if (Common.languageCode == "zh-CN")
                                    {
                                        LayUINotify.ShowInfo("性别不能为空！");
                                    }
                                    else
                                    {
                                        LayUINotify.ShowInfo("Tip", "Gender is required!");
                                    }
                                    //LayUINotify.ShowInfo("性别不能为空！");
                                    return;
                                }
                                if (patient.P_ID.Length > 25)
                                {
                                    if (Common.languageCode == "zh-CN")
                                    {
                                        LayUINotify.ShowInfo("病人ID过长！");
                                    }
                                    else
                                    {
                                        LayUINotify.ShowInfo("Tip", "ID is too long!");
                                    }
                                    //LayUINotify.ShowInfo("病人ID过长！");
                                    return;
                                }

                                if (service.PatidExist(patient.P_ID))
                                {
                                    if (Common.languageCode == "zh-CN")
                                    {
                                        LayUINotify.ShowInfo($"患者 {patient.Name} 已存在于数据库");
                                    }
                                    else
                                    {
                                        LayUINotify.ShowInfo($"patient {patient.Name} is already in the database");
                                    }
                                    //LayUINotify.ShowInfo($"患者 {patient.Name} 已存在于数据库");
                                }
                                else
                                {
                                    bindList.Add(patient);
                                    if (!patientService.AddPatient(patient))
                                    {
                                        if (Common.languageCode == "zh-CN")
                                        {
                                            LayUINotify.ShowInfo($"患者 {patient.Name} 的信息保存到数据库失败。");
                                        }
                                        else
                                        {
                                            LayUINotify.ShowInfo($"Failed to save {patient.Name}'s information to the database");
                                        }
                                        //MessageBox.Show($"患者 {patient.Name} 的信息保存到数据库失败。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                                    }
                                }

                            }
                            

                        }

                        // 将数据绑定到DataGrid
                        grid.ItemsSource = bindList;
                        openPatientsModel.RecordCount = bindList.Count;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Failed when import: {ex.Message}", "error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                if (Common.languageCode == "zh-CN")
                {
                    MessageBox.Show("请选择有效的CSV文件路径");
                }
                else
                {
                    MessageBox.Show("Please select a valid CSV file path");
                }
            }
        }


        private void ImpSelBtn_Click(object sender, RoutedEventArgs e)
        {
            var selectedPatients = patientList.Where(p => p.IsSelected).ToList();
            if (selectedPatients.Count == 0)
            {
                if (Common.languageCode == "zh-CN")
                {
                    MessageBox.Show("请选择要导出的病人信息");
                }
                else
                {
                    MessageBox.Show("Please select the patient information to export");
                }
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*",
                FileName = "导出病人信息.csv"
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    using (var writer = new StreamWriter(saveFileDialog.FileName, false, Encoding.UTF8))
                    {
                        writer.WriteLine("姓名,病人ID,性别,生日,地址,电话,邮箱,创建日期");
                        foreach (var patient in selectedPatients)
                        {
                            string p_IDFormatted = $"=\"{patient.P_ID}\"";
                            writer.WriteLine($"{patient.Name},{p_IDFormatted},{patient.SEX},{patient.Birth:yyyy-MM-dd},{patient.Adreess},{patient.PhoneNum},{patient.Email},{patient.InsertDate:yyyy-MM-dd}");
                        }
                    }
                    MessageBox.Show("病人信息导出成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导出时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void ModelBtn_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*",
                FileName = "病人信息模板.csv"
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    using (var writer = new StreamWriter(saveFileDialog.FileName, false, Encoding.UTF8))
                    {
                        writer.WriteLine("姓名,病人ID,性别,生日,地址,电话,邮箱,创建日期");

                        writer.WriteLine("张三,=\"001\",男,1990-01-01,北京市海淀区,12345678901,email@example.com,2023-01-01");
                        writer.WriteLine("李四,=\"002\",女,2001-09-19,上海市宝山区,98765432101,email2@example.com,2023-02-01");
                    }
                    if (Common.languageCode == "zh-CN")
                    {
                        MessageBox.Show("模板导出成功");
                    }
                    else
                    {
                        MessageBox.Show("Template exported successfully");
                    }
                   // MessageBox.Show("模板导出成功");
                }
                catch (Exception)
                {
                    
                }
            }
        }



        private void ConcelBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Paginator_Loaded(object sender, RoutedEventArgs e)
        {
            patientList = getPatient();
            openPatientsModel.RecordCount = patientList.Count;
            LoadDataWithPagination(1, openPatientsModel.PageSize);
        }

        private void Paginator_PageChanged(object arg1, Control.PageEventArgs arg2)
        {
            Paginator paginator = arg1 as Paginator;
            LoadDataWithPagination(paginator.Page, paginator.PageSize);
        }

        private void LoadDataWithPagination(int page, int pageSize)
        {
            grid.ItemsSource = null;

            IEnumerable<PatientModel> dataSource;

            // 根据当前数据源类型来获取不同的数据源
            if (currentDataSourceType == DataSourceType.CSV)
            {
                dataSource = bindList.Skip((page - 1) * pageSize).Take(pageSize);
            }
            else // 数据库来源
            {
                dataSource = patientList.Skip((page - 1) * pageSize).Take(pageSize);
            }

            grid.ItemsSource = dataSource;
        }

        private List<PatientModel> getPatient()
        {
            return patientService.GetAllPatients();
        }
    }
}
